$(function () {
    getOrganizationTree();
    initData();
    treeSearch("ss", "treeContent") // 绑定树搜索功能
})

//加载机构树信息
function getOrganizationTree() {
    //加载机构树，当前登录人所在的机构信息
    $.messager.progress({text: '正在加载中...',});
    $.ajax({
            type: "post",
            url: system + "/organization/queryOrganizationTree",
            dataType: "json",
            success: function (data) {
                $.messager.progress('close');
                if (successcode != data.code) {
                    return errorHandle(data);
                }
                $('#treeContent').tree({
                    cascadeCheck: false,
                    checkbox: false,
                    lines: false,
                    data: data.data,
                    onClick: function (node) {
                    },  //双击事件
                    onDblClick: function (node) {
                        viewOrganization();
                    }, onContextMenu: function (e, node) {
                        //显示上下文菜单:就是显示右键菜单
                        e.preventDefault();
                        $(this).tree('select', node.target);
                        $('#nav').menu('show', {
                            left: e.pageX,
                            top: e.pageY
                        });
                        $('#nav').menu({
                            onClick: function (item) { // 根据选择的id判断选中的是添加，修改，还是删除
                                if ("2" == item.id) {
                                    addOrganization();
                                }
                                if ("3" == item.id) {
                                    editOrganization();
                                }
                                if ("4" == item.id) {
                                    delOrganization();
                                }
                            }
                        })
                    },
                    formatter: function (node) {
                        //显示父节点含有子节点个数
                        var s = node.text;
                        if (node.children) {
                            s += ' <span style=\'color:blue\'>(' + node.children.length + ')</span>';
                        }
                        return s;
                    }
                })
            }, error: function (data) {
                $.messager.progress('close');
                $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
            }
        }
    );
}

// 初始化加载下拉框的值
function initData() {
    $.ajax({
            type: "post",
            url: system + "/organization/init",
            success: function (data) {
                if (successcode != data.code) {
                    return errorHandle(data);
                }
                var status = data.data.status;
                var type = data.data.type;
                var listOrganization = data.data.listOrganization;
                if (!isNull(type)) {
                    $("#type").combobox("loadData", type);
                }
                if (!isNull(listOrganization)) {
                    //在数组第一个追加
                    listOrganization.unshift({"text": "==无上级==", "id": '0', "pId": "", "iconCls": "icon-bricks"});
                    $("#parentId").combotree("loadData", listOrganization);
                }
            }, error: function (data) {
                $.messager.progress('close');
                $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
            }
        }
    );
}

/**
 * 查看机构信息弹出框
 */
function viewOrganization() {
    $('#myform').form('disableValidation');//清除验证样式
    $('#dlg').dialog({
        title: "查看机构信息",
        buttons: [{
            text: '返回',
            iconCls: 'icon-back',
            handler: function () {
                $('#dlg').dialog('close');
            }
        }
        ]
    }).dialog('open');
    getOrganizationInfo();
}


/**
 * 添加机构信息弹出框
 */
function addOrganization() {
    $("#myform").form('clear');//添加之前清空表达信息
    $('#myform').form('enableValidation');//设置验证样式
    $('#dlg').dialog({
        title: "新增机构信息",
        buttons: [{
            text: '保存',
            iconCls: 'icon-save',
            handler: function () {
                saveItemOrganization(1);
            }
        }, {
            text: '返回',
            iconCls: 'icon-back',
            handler: function () {
                $('#dlg').dialog('close');
            }
        }
        ]
    }).dialog('open');
    $('#type').combobox('selectedIndex', 0); //选中第一个
    var node = $("#treeContent").tree('getSelected');
    $('#parentId').combotree('setValue', node.id);
}

/**
 * 修改机构信息
 */
function editOrganization() {
    $('#myform').form('enableValidation');//设置验证样式
    $('#dlg').dialog({
        title: "编辑机构信息",
        buttons: [{
            text: '保存',
            iconCls: 'icon-save',
            handler: function () {
                saveItemOrganization(2);
            }
        }, {
            text: '返回',
            iconCls: 'icon-back',
            handler: function () {
                $('#dlg').dialog('close');
            }
        }
        ]
    }).dialog('open');
    getOrganizationInfo();
}

// 删除机构信息
function delOrganization() {
    var node = $("#treeContent").tree('getSelected');
    $.messager.confirm('系统提示', '确定要删除【' + node.text + '】机构以及下级所有机构信息吗？', function (param) {
        if (!param) {
            return;
        }
        $.messager.progress({text: '正在处理中...',});
        $.ajax({
                type: "post",
                url: system + "/organization/delOrganization",
                dataType: "json",
                data: {
                    id: node.id
                },
                success: function (data) {
                    $.messager.progress('close');
                    if (successcode != data.code) {
                        return errorHandle(data);
                    }
                    getOrganizationTree();//刷新树
                    initData();
                    $.messager.show({title: '系统提示', msg: data.message});
                }, error: function (data) {
                    $.messager.progress('close');
                    $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
                }
            }
        );

    });
}

/**
 * 点击树节点加载对应机构信息
 * @param orgId
 */
function getOrganizationInfo() {
    var node = $("#treeContent").tree('getSelected');
    $.messager.progress({text: '正在加载中...',});
    $.ajax({
            type: "post",
            url: system + "/organization/queryOrganizationInfo",
            dataType: "json",
            data: {
                orgId: node.id
            },
            success: function (data) {
                $.messager.progress('close');
                if (successcode != data.code) {
                    return errorHandle(data);
                }
                $('#myform').form('load', data.data);//页面赋值
            }, error: function (data) {
                $.messager.progress('close');
                $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
            }
        }
    );
}

//保存机构信息
function saveItemOrganization(ftype) {
    //验证表单信息
    if (!$("#myform").form('validate')) { //验证表单信息
        return;
    }
    var url = system + "/organization/editOrganization";
    if (1 == ftype) {
        url = system + "/organization/addOrganization";
    }
    $.messager.confirm('系统提示', "确定保存机构信息吗？", function (parm) {
        if (!parm) {
            return;
        }
        $('#myform').form('submit', {
            url: url,
            onSubmit: function () {
                $.messager.progress({text: '正在处理中...',});
            }, success: function (data) {
                $.messager.progress('close');
                try {
                    data = JSON.parse(data);
                    if (successcode != data.code) {
                        return errorHandle(data);
                    }
                    //关闭弹出窗口
                    $('#dlg').dialog('close');
                    getOrganizationTree();//刷新树
                    initData();
                    $.messager.show({title: '系统提示', msg: data.message});
                } catch (e) {
                    $.messager.progress('close');
                    $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
                }
            }
        });
    });
}


//读取文件
function readExcel(fileName) {
    //文件后缀格式
    if (!/\.(xls|xlsx|XLS|XLSX)$/.test(fileName)) {
        $.messager.alert('系统提示', '错误的文件类型，请下载对应的模板', 'error');
        return;
    }
    $('#subXls').form('submit', {
        url: system + "/organization/readExcel",
        onSubmit: function (param) {
            $.messager.progress({text: '正在处理中...'});
        }, success: function (data) {
            $.messager.progress('close');
            data = JSON.parse(data);
            if (successcode != data.code) {
                $("#readXls").val("");
                return errorHandle(data);
            }
            $.messager.show({title: '系统提示', msg: data.message});
            getOrganizationTree();//刷新树
        }, error: function (data) {
            $("#readXls").val("");
            $.messager.progress('close');
            $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
        }
    });
}
